<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_unilevel($in_date){
/*
This function calculate the unilevel bonus for all the sales that is of second sale and onwards for a member (first sale of a member the
commission is calculated using different calculation methods). It will credit to the upline of the purchase owner up to 7 levels, according
to the qualification of an upline in the unilevel. Sales will also include maintenance volume from previous month.

Payment of bonus is according to the placement hierarchy.
*/

	//globalize access to unilevel, min_maintain
	global $vars;
	$db=$vars["db"];
	$unilevel = $vars['unilevel'];
	$min_maintain = $vars['min_maintain'];
	$maintenance_percent = $vars['maintenance_percent'];
	$max_maintain = $vars['max_maintain'];
	//calc_date = get the start and end of the input in_date
	$year = date("Y", strtotime($in_date));
	$month = date("n", strtotime($in_date));
	$calc_date['start']=date('Y-m-d H:i:s', mktime(0, 0, 0, $month, 1, $year));
	$calc_date['end']=date('Y-m-d H:i:s', mktime(23, 59, 59, $month+1, 0, $year));
	$last_month_time = mktime(0, 0, 0, $month-1, 1, $year);
	$last_month_year = date('Y', $last_month_time);
	$last_month_month = date('n', $last_month_time);
	$maintain_time=mktime(0, 0, 0, $month+1, 1, $year);
	$maintain_year = date("Y", $maintain_time);
	$maintain_month = date("n", $maintain_time);
	//max_level = get the maximum level of unilevel (7)
	$max_level = count($unilevel);
	
	//sales = get all the sales that is confirmed and is not first sale of a member within the date of input in_date
	$t = @mysql_num_rows($r=mysql_query("select * from $db->purchase where first_sale!='y' and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"));
	//foreach sales
	for($i=0;$i<$t;$i++){
		$sale = mysql_fetch_assoc($r);
		$uid = $sale['uid'];
		$downline_id = $uid;
		$level = $actual_level = 1;
		do{
			if (!isset($users[$downline_id])){
				$users[$downline_id] = get_user_short_detail_by_id($downline_id);
			}
			$upline_id = $users[$downline_id]['matrix_upline'];
			if ($upline_id){
				if (!isset($users[$upline_id])){
					$users[$upline_id] = get_user_short_detail_by_id($upline_id);
				}
				$upline_volume = calc_personal_sales($upline_id, $calc_date['start'], $calc_date['end']);
				$total_downline = @mysql_result(mysql_query("select count(*) from $db->users where matrix_upline='$upline_id' and cdate<='$calc_date[end]'"), 0) or 0;
				$total_sponsor = @mysql_result(mysql_query("select count(*) from $db->users where ref='$upline_id' and cdate<='$calc_date[end]'"), 0) or 0;
				if ($upline_volume >= $min_maintain && $total_downline >= $unilevel[$level]['downline'] && $total_sponsor >= $unilevel[$level]['sponsor']){
					$comm_percent = $unilevel[$level]['percent'];
					$comm_amount = round($comm_percent * $sale['total_bv'] / 100, 2);
					//insert the commission into the member_comm table with type = unilevel, uid = upline_id, amount = comm_amount, percent = comm_percent, year, month, datetime
					$sql="insert into $db->member_comm (uid, from_uid, type, cid, amount, level, level2, percent, year, month, status, cdate) values ('$upline_id', '$uid', 'u', '$sale[id]', '$comm_amount', '$level', '$actual_level', '$comm_percent', '$year', '$month', 'confirmed', '".ndate('Y-m-d H:i:s')."')";
					$insert_comm_detail="UID: $upline_id Sale ID: $sale[id] Amount: $comm_amount Level: $level Percent: $comm_percent%<br />\n";
					if(!mysql_query($sql)){
						$insert_error.=$insert_comm_detail."SQL: $sql<br />\n";
					}else{
						$insert_success.=$insert_comm_detail;
					}
					//member_comm[upline_id] += comm_amount
					$member_comm[$upline_id] += $comm_amount;
					$level++;
				}
			}
			$downline_id = $upline_id;
			$actual_level++;
		}while ($level <= $max_level && $upline_id);
	}
	
	//maintain = get all the maintenance that is within the date of input in_date
	$t = @mysql_num_rows($r=mysql_query("select * from $db->member_maintain where year='$year' and month='$month'"));
	//foreach sales
	for($i=0;$i<$t;$i++){
		$maintain = mysql_fetch_assoc($r);
		//uid = maintain[uid]
		$uid = $maintain['uid'];
		$downline_id = $uid;
		$level = $actual_level = 1;
		do{
			if (!isset($users[$downline_id])){
				$users[$downline_id] = get_user_short_detail_by_id($downline_id);
			}
			$upline_id = $users[$downline_id]['matrix_upline'];
			if ($upline_id){
				if (!isset($users[$upline_id])){
					$users[$upline_id] = get_user_short_detail_by_id($upline_id);
				}
				$upline_volume = calc_personal_sales($upline_id, $calc_date['start'], $calc_date['end']);
				$total_downline = @mysql_result(mysql_query("select count(*) from $db->users where matrix_upline='$upline_id' and cdate<='$calc_date[end]'"), 0) or 0;
				$total_sponsor = @mysql_result(mysql_query("select count(*) from $db->users where ref='$upline_id' and cdate<='$calc_date[end]'"), 0) or 0;
				if ($upline_volume >= $min_maintain && $total_downline >= $unilevel[$level]['downline'] && $total_sponsor >= $unilevel[$level]['sponsor']){
					$comm_percent = $unilevel[$level]['percent'];
					$comm_amount = round($comm_percent * $maintain['amount'] / 100, 2);
					//insert the commission into the member_comm table with type = unilevel, uid = upline_id, amount = comm_amount, percent = comm_percent, year, month, datetime
					$sql="insert into $db->member_comm (uid, from_uid, type, nid, amount, level, level2, percent, year, month, status, cdate) values ('$upline_id', '$uid', 'u', '$maintain[id]', '$comm_amount', '$level', '$actual_level', '$comm_percent', '$year', '$month', 'confirmed', '".ndate('Y-m-d H:i:s')."')";
					$insert_comm_detail="UID: $upline_id Maintain ID: $maintain[id] Amount: $comm_amount Level: $level Percent: $comm_percent%<br />\n";
					if(!mysql_query($sql)){
						$insert_error.=$insert_comm_detail."SQL: $sql<br />\n";
					}else{
						$insert_success.=$insert_comm_detail;
					}
					//member_comm[upline_id] += comm_amount
					$member_comm[$upline_id] += $comm_amount;
					$level++;
				}
			}
			$actual_level++;
			$downline_id = $upline_id;
		}while ($level <= $max_level && $upline_id);
	}
	
	if ($member_comm){
		foreach ($member_comm as $uid => $amount){
			$total_maintain_amount = $maintain_amount = round($amount * $maintenance_percent / 100, 2);
			$next_month_maintain = @mysql_result(mysql_query("select sum(amount) from $db->member_maintain where uid='$uid' and year='$maintain_year' and month='$maintain_month'"), 0) or 0;
			if($next_month_maintain < $max_maintain){
				if($maintain_amount + $next_month_maintain > $max_maintain){
					$maintain_amount = $max_maintain - $next_month_maintain;
				}
				//insert into member_maintain with uid = uid, type = plana, comm_type = sponsor bonus, percent = maintain[plana], amount = maintain_plana, pv = maintain_value_to_pv, date
				$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate)
				values ('$uid', 'u', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')";
				if(!mysql_query($sql)){
					$insert_main_err.="UID: $uid, comm code: u, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month\n";
				}
			}else{
				$maintain_amount = 0;
			}
			
			$actual_amount = $amount - $total_maintain_amount;
			if(!mysql_query($sql="update $db->users set ewallet=ewallet+$actual_amount where id='$uid' limit 1")){
				$update_ew_err.="UID: $uid, amount: $actual_amount\n";
			}elseif(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$amount', '".addslashes("Credited $vars[currency]".number_format($amount, 2)." from bulk unilevel commission received.")."', '".ndate()."')")){
				$insert_ewrec_err.=$sql."\n";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal += $amount;
				@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
			
			if($maintain_amount > 0){
				//insert ewallet record for maintenance
				if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$maintain_amount', '".addslashes("Debited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk unilevel commission received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $maintain_amount;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				//update member swallet = swallet + maintain_amount
				if(!mysql_query($sql="update $db->users set swallet=swallet+$maintain_amount where id='$uid' limit 1")){
					$update_sw_err.="UID: $uid, amount: $maintain_amount\n";
				}elseif(!mysql_query($sql="insert into $db->member_swallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$maintain_amount', '".addslashes("Credited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk unilevel commission received.")."', '".ndate()."')")){
					$insert_swrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_swallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $maintain_amount;
					@mysql_query("update $db->member_swallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
			//mall point
			$mall_point = $total_maintain_amount - $maintain_amount;
			if($mall_point > 0){
				//insert ewallet record for maintenance
				if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$mall_point', '".addslashes("Debited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk unilevel commission received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $mall_point;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				//update member mwallet = mwallet + mall_point
				if(!mysql_query($sql="update $db->users set mwallet=mwallet+$mall_point where id='$uid' limit 1")){
					$update_mw_err.="UID: $uid, amount: $mall_point\n";
				}elseif(!mysql_query($sql="insert into $db->member_mwallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$mall_point', '".addslashes("Credited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk unilevel commission received.")."', '".ndate()."')")){
					$insert_mwrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_mwallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $mall_point;
					@mysql_query("update $db->member_mwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
		}
	}
	
	if($insert_error || $insert_main_err){
		$status = false;
	}else{
		$status = true;
	}
	
	$errmsg = ($insert_error? "Failed Unilevel Commission Calculation:<br />\n<br />\n$insert_error" : "").
	($update_ew_err? "\nError crediting $vars[ewallet_title]:\n\n$update_ew_err" : "").
	($insert_ewrec_err? "\nError crediting $vars[ewallet_title] transactin record:\n\n$insert_ewrec_err" : "").
	($update_sw_err? "\nError crediting $vars[swallet_title]:\n\n$update_sw_err" : "").
	($insert_swrec_err? "\nError crediting $vars[swallet_title] transactin record:\n\n$insert_swrec_err" : "").
	($update_mw_err? "\nError crediting $vars[mwallet_title]:\n\n$update_mw_err" : "").
	($insert_mwrec_err? "\nError crediting $vars[mwallet_title] transactin record:\n\n$insert_mwrec_err" : "");
	
	return array('status'=>$status, 'errmsg'=>$errmsg);
}
?>